package cz.vse.javaee.photoMan;

import javax.jms.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Apr 26, 2010
 * Time: 9:48:49 PM
 * To change this template use File | Settings | File Templates.
 */
public class Main {


    public static void main(String[] args) throws Exception {
        String photoDir = args[0];

        com.sun.messaging.ConnectionFactory  myFactory = new com.sun.messaging.ConnectionFactory();
        Connection connection = myFactory.createConnection();
        try {
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            Destination queue = new com.sun.messaging.Queue("exportQueue");
            MessageConsumer consumer = session.createConsumer(queue);
            connection.start();

            BytesMessage message;
            do {
                message = (BytesMessage) consumer.receive(1000);
                if (message != null) {
                    storePhoto(message, photoDir);
                }
            } while (message != null);
        } finally {
            connection.close();
        }
    }

    private static void storePhoto(BytesMessage message, String photoDir) throws JMSException, IOException {
        String photoName = message.getStringProperty("name");

        System.out.println("Exportuji " + photoName);

        File photoFile = new File(new File(photoDir), photoName + ".png");
        FileOutputStream fos = new FileOutputStream(photoFile);
        byte[] image = new byte[(int) message.getBodyLength()];
        message.readBytes(image);
        fos.write(image);
        fos.close();
    }


}
